<script lang="ts" setup>
import { useSettingStore } from "./stores/settingStore"
import { nextTick, onMounted, onUnmounted, ref, toRaw } from 'vue'
import SimpleList from '@/components/utils/SimpleList.vue'
import ButtonInput from '@/components/utils/ButtonInput.vue'
import { ElMessage, resultProps } from 'element-plus'
const electron = require("electron")

let settingStore = useSettingStore()
let selectedGroup = ref<any>(null)

// 初始化数据
let initData = function () {
  electron.ipcRenderer.invoke('getData').then((data: any) => {
    console.log('Loaded setting data:', data);
    // 使用函数形式的$patch确保响应式更新
    settingStore.initData(data.settings);
    console.log(settingStore.exportGroups)
  });
}
  initData()

// 处理列表项点击事件
let handleClick = (id: number) => {
  selectedGroup.value = settingStore.getExportGroup(id)
}

// 处理添加事件
let handleAdd = () => {
  settingStore.addGroup("group")
}

// 处理删除事件
let handleDelete = (id: number) => {
  // 确认删除
  electron.ipcRenderer.invoke('confirmDelete', `确定要删除分组 ${settingStore.getExportGroupName(id)} 吗？`).then((result: boolean) => {
    if (result) {
      // 执行删除
      settingStore.exportGroups = settingStore.exportGroups.filter(group => group.id !== id)
      selectedGroup.value = null
      ElMessage.success('删除成功')
    }
  })
}

// 监听数据更新
const handleDataUpdated = (event: any, data: any) => {
  // 更新选中的分组信息
  if (selectedGroup.value && data.exportGroups) {
    const updatedGroup = data.exportGroups.find((group: any) => group.id === selectedGroup.value.id)
    if (updatedGroup) {
      selectedGroup.value = updatedGroup
    }
  }
}

// 更新分组名称
let updateGroupName = (value: string) => {
  if (selectedGroup.value) {
    selectedGroup.value.name = value
    saveData()
  }
}

// 更新分组描述
let updateGroupDesc = (value: string) => {
  if (selectedGroup.value) {
    selectedGroup.value.desc = value
    nextTick(() => {
      saveData()
    })
  }
}

// 保存数据
let saveData = function () {
  electron.ipcRenderer.invoke('saveSettingStore', toRaw(settingStore.$state)).then((result: any) => {
    if (result.success) {
      // ElMessage.success('保存成功')
    }
  }).catch((error: any) => {
    ElMessage.error('保存失败')
    console.log(error)
  })
}

// 定义添加分组的处理函数
const addGroupHandler = (event: any, group: any) => {
  settingStore.addGroup(group.name, group.desc)
  saveData()
}

onMounted(() => {
  electron.ipcRenderer.on('dataUpdated', handleDataUpdated)
  // 监听添加分组事件
  electron.ipcRenderer.on('addGroup', addGroupHandler)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  electron.ipcRenderer.removeListener('dataUpdated', handleDataUpdated)
  electron.ipcRenderer.removeListener('addGroup', addGroupHandler)
})
</script>

<template>
  <div class="setting-container">
    <div class="header">
      <el-text size="large" type="primary">导出分组设置</el-text>
    </div>
    <div class="content">
      <div class="list-container">
        <SimpleList
          :list="settingStore.exportGroups"
          @click="handleClick"
          @add="handleAdd"
          @delete="handleDelete"
        />
      </div>
      <div class="detail-container" v-if="selectedGroup">
        <div class="detail-item">
          <el-text>名称：</el-text>
          <ButtonInput v-model="selectedGroup.name" @update:modelValue="updateGroupName" />
        </div>
        <div class="detail-item">
          <el-text>描述：</el-text>
          <ButtonInput v-model="selectedGroup.desc" @update:modelValue="updateGroupDesc" />
        </div>
      </div>
      <div class="no-selection" v-else>
        <el-text>请选择一个导出分组</el-text>
      </div>
    </div>
  </div>
</template>

<style scoped>
.setting-container {
  padding: 20px;
  height: 100vh;
  box-sizing: border-box;
}

.header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.content {
  display: flex;
  gap: 20px;
  height: calc(100% - 60px);
}

.list-container {
  width: 300px;
  display: flex;
  flex-direction: column;
}

.detail-container {
  flex: 1;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.no-selection {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  background-color: #f5f7fa;
  border-radius: 8px;
}
</style>